from django.conf import settings
from django.contrib.auth.backends import ModelBackend
import re

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from users.models import User

"""自定义管理类的使用"""
def get_by_natural_key(count):
    """通过前端传入的用户名或者手机匹配"""
    try:
        if re.match(r'^1[3-9]\d{9}', count):
            user = User.objects.get(mobile=count)
        else:
            user = User.objects.get(username=count)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义认证类：目的是实现多帐号登陆"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        # user = get_by_natural_key(username)
        # if user and user.check_password(password):
        #     return user
        try:

            user = User.objects.get(username=username)
        except:
            # 如果未查到数据，则返回None，用于后续判断
            try:
                user = User.objects.get(mobile=username)
            except:
                return None
        if request == None:
            # 后台管理站点登陆的时候(request为None)
            # 才需要，判断是否是超级管理员
            if not user.is_staff:
                # 如果是超级管理元，才允许后续的操作
                return None
        # 判断密码
        if user.check_password(password):
            return user
        else:
            return None


def generate_verify_email_url(user):
    """生成用户邮箱激活页面加密"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    data = {'user_id': user.id, 'email': user.email}
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + "?token=" + token
    return verify_url


def check_verify_email_token(token):
    """对token进行解密"""
    serializer = Serializer(settings.SECRET_KEY, 3600*24)
    try:
        data = serializer.loads(token)
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
            return user
        except User.DoesNotExist:
            return None
    except BadData:
        return None


